<?php

namespace App\Models;

use App\Clients\CrmClient;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class Project extends Model
{
    use HasFactory;
    use HasDateTimeFormatter;

    const CACHE_CUSTOMER_TYPE_KEY = '_cache_customer_type_key__';
    protected $fillable = [
        'name',
        'customer_type',
        'customer_type_text',
        'rule_type',
        'rules'
    ];

    protected $casts = [
        'rules' => 'json'
    ];
    protected static $rules = null;

    public static function getRules()
    {
        if (!static::$rules)
            static::$rules = static::query()->get();

        return static::$rules;
    }

    public static function checkProject($clue)
    {
        $rules = static::getRules();
        foreach ($rules as $rule) {
            if (DispatchRule::validateClueOfRule($clue, $rule->rules, $rule->rule_type))
                return $rule;
        }
        return null;
    }

    public static function getCustomerList()
    {
        $result = Cache::get(self::CACHE_CUSTOMER_TYPE_KEY);
        if (!$result) {
            $list = CrmClient::make()->getCustomerTypeList();
            if ($list) {
                $result = $list;
                Cache::put(self::CACHE_CUSTOMER_TYPE_KEY, $list);
            }
        }

        return $result;
    }

}
